#include "task.h"
#include <cfg_param.h>
#include <hal_socket.h>
#include "hal_driver.h"
#include "hal_configer.h"
#include "hal_current.h"
#include "hal_temp.h"
#include "sys_log.h"
#include "socket_handle.h"
#include "hal_tlv.h"
#include "common.h"
#include "hal_eeprom.h"
#include "socket_handle.h"
#include "hal_EEpromWR.h"
#include "cfg_drive.h"

extern struct PacketQueue g_MyQueue;
extern uint32_t TA_CHANNEL_LD_ON_PIN_STATE;

TempCurrentParaSt g_TempCurrentRealValue;

static void UartRcvDeal();
static void LaserReadDeal();
static void DriverProtectDeal();

uint32_t i = 0, j = 0;
uint16_t pritect_cnt[2] = {0};

float tempData = 0;
int tempFlag;
float tempSet = 25.00;
int protec_chn1 = 0;
int protec_chn2 = 0;
float currentData = 0;
float pd_currentData = 0;
float currentChangeData = 0;

float seedCurrent[10000];
float taCurrent[10000];
float pdCurrent[10000];
int seedCurIndex = 0;
int taCurIndex = 0;
int pdCurIndex = 0;
int storeFlag = 0;
int runFlag = 0;
/*
TA调式
*/
int modeChangeFlag = 0;//默认恒流
int dfbWorkingFlag = 1;
float pdCurSet = 0;
float taCurSet = 0;

float seedVoltage = 0;
float taVoltage = 0;
float seedCur = 0;
float taCur = 0;
float seedTemp = 0;
float taTemp = 0;
float pdCur = 0;
float taTempCur = 0;
float taTempSet = 25;
int taTempSetFlag = 0;
float taCurReal = 0;
float seedCurSet = 0;

float seedTempSet = 25;

float seedTempCur = 0;

int taWorkingFlag = 1;

int mode = 0;

/*
**参数列表**
*/
int workingModeSetFlag = 0;

void task_laser()
{
    SLOG_I("laser task_laser start \t\r\n");

    LaserInit();
	
		EEPromParaSt EEPromPara;
		memset(&EEPromPara, 0, sizeof(EEPromPara));
		float temp = 25.00;
		float cur = 0.00;
		float power = 0.00;
		Temp_Copy_To_EEPROM(LASER_NUMBER_CHAN_1, temp, EEPromPara.EEp_CH1_Temp);
    Current_Copy_To_EEPROM(LASER_NUMBER_CHAN_1, cur, EEPromPara.EEp_CH1_Cur);
				
		Temp_Copy_To_EEPROM(LASER_NUMBER_CHAN_2, temp, EEPromPara.EEp_CH2_Temp);
    Current_Copy_To_EEPROM(LASER_NUMBER_CHAN_2, cur, EEPromPara.EEp_CH2_Cur);
    Power_Copy_To_EEPROM(LASER_NUMBER_CHAN_2, power, EEPromPara.PD_Current);
				
		HAL_I2cEEPromWrite(EEPROM_TEMP_CURRENT_SEED_ADDR, (uint8_t *)EEPromPara.EEp_CH1_Cur, sizeof(EEPromParaSt));
		
		//恒流，默认恒流模式
		HAL_SetWorkingMode(0);
	
		systick_delay_s(1);
		
		/*LASER_GPIO_WRITE_PIN(CH1_REG_CPTART, GPIO_PIN_SET);
		systick_delay_ms(10);
		LASER_GPIO_WRITE_PIN(CH1_REG_CPTART, GPIO_PIN_RESET);
		systick_delay_ms(10);*/
		
		HAL_CurrentDrivePinEnable(LASER_NUMBER_CHAN_2);
		TA_CHANNEL_LD_ON_PIN_STATE = GPIO_PIN_SET;
			
    while (1)
    {
        if (i++ > LASER_APP_LED_FRE)
        {
            HAL_GPIO_TogglePin(APP_LED_GPIOPORT, APP_LED_PIN);
						i = 0;
        }
				if(j++ > LASER_APP_LOG_TIMER)
				{
						SLOG_I("laser --------------------task_laser is running-------------------- \t\r\n");
						j = 0;
				}

        LaserReadDeal();
				
				/*LASER_GPIO_WRITE_PIN(CH1_REG_CPTART, GPIO_PIN_RESET);
				systick_delay_ms(10);*/
				

        //DriverProtectDeal();

        //UartRcvDeal();
				
				mode = HAL_GetWorkingMode();
				
				//更改工作模式，要关闭电源
				if(workingModeSetFlag){
					//关闭电源
					if(mode)
						HAL_SetWorkingMode(0);
					else
						HAL_SetWorkingMode(1);
				}
				
				//debug模式下，设置标志位判断，设置DFB电流温度、TA电流温度
				//DFB设置
				/*if(dfbParamSetFlag){
					//电流源开关
					HAL_CurrentDrivePinEnable(LASER_NUMBER_CHAN_1);
					Temp_Direct_Change(dfbTempSet,LASER_NUMBER_CHAN_1);
					systick_delay_s(1);
					SeedCurrent_Slow_Change(dfbCurSet,LASER_NUMBER_CHAN_1);
					systick_delay_s(1);
				}
				
				//TA设置
				if(taParamSetFlag){
					//电流源开关
					TA_CHANNEL_LD_ON_PIN_STATE = GPIO_PIN_SET;
					Temp_Direct_Change(taTempSet,LASER_NUMBER_CHAN_2);
					systick_delay_s(1);
					if(TA_WORKING_MODE == TA_POWER_MODE){
						PDCurrent_Slow_Change(taPDSet, LASER_NUMBER_CHAN_2);
					}else if(TA_WORKING_MODE == TA_CURRENT_MODE){
						TACurrent_Slow_Change(taCurSet, LASER_NUMBER_CHAN_2);
					}
				}*/
				
				//前期设置EEPROM的值
				
				
				/*if(tempFlag){
					//Temp_Direct_Change(25, LASER_NUMBER_CHAN_1);
					Temp_Direct_Change(taTempSet, LASER_NUMBER_CHAN_1);
					HAL_CurrentDrivePinEnable(LASER_NUMBER_CHAN_1);
					//systick_delay_s(1);
					HAL_CurrentDrivePinEnable(LASER_NUMBER_CHAN_2);
					TA_CHANNEL_LD_ON_PIN_STATE = GPIO_PIN_SET;
					//systick_delay_s(1);
					SeedCurrent_Slow_Change(currentChangeData, LASER_NUMBER_CHAN_1);
					//systick_delay_s(1);
					if(runFlag){
						hal_PDCurrentSlowChange(taCurSet, LASER_NUMBER_CHAN_2);
					}
				}*/
				
				
				
				if(dfbWorkingFlag){
					HAL_CurrentDrivePinEnable(LASER_NUMBER_CHAN_1);
					systick_delay_s(1);
					Temp_Direct_Change(seedTempSet,LASER_NUMBER_CHAN_1);
					systick_delay_s(1);
					//SeedCurrent_Slow_Change(seedCurSet,LASER_NUMBER_CHAN_1);
					hal_SeedCurrentSlowChange(seedCurSet, CURRENT_SEPARAT_SEED,LASER_NUMBER_CHAN_1);
					systick_delay_s(1);
					Temp_Direct_Change(taTempSet,LASER_NUMBER_CHAN_2);
					systick_delay_s(1);
					HAL_CurrentDrivePinEnable(LASER_NUMBER_CHAN_2);
					dfbWorkingFlag = 0;
					
				}
				
				/*if(taTempSetFlag){
					systick_delay_s(1);
					Temp_Direct_Change(taTempSet,LASER_NUMBER_CHAN_2);
					systick_delay_s(1);
				}*/
				
				/*if(modeChangeFlag){
					//恒功率
					HAL_SetWorkingMode(1);
				}else{
					//恒流
					HAL_SetWorkingMode(0);
				}*/
				
				if(taWorkingFlag){
					
					systick_delay_s(1);
					//hal_TACurrentSlowChange(taCurSet,SAMPCUR_TYPE_WORK_CURRENT);//恒流工作模式
					hal_SeedCurrentSlowChange(taCurSet, CURRENT_SEPARAT_TA, LASER_NUMBER_CHAN_2);
					taWorkingFlag = 0;
				}
			
				
				
				
				/*if(taWorkingFlag){
					hal_PDCurrentSlowChange(pdCurSet, LASER_NUMBER_CHAN_2);
				}*/
    }
}

static void LaserReadDeal()
{
    // 激光器温度/温控电流读取 0.8ms/0.2ms
    g_TempCurrentRealValue.Temperature_Chn_1    = HAL_AD7689SpiReadTempOrTempCtrCurReal(ADC7689_LASER_TEMP_CHAN_1, AD7689_LASER_TEMP_REGTOT, LASER_NUMBER_CHAN_1);
    g_TempCurrentRealValue.Temperature_Chn_2    = HAL_AD7689SpiReadTempOrTempCtrCurReal(ADC7689_LASER_TEMP_CHAN_2, AD7689_LASER_TEMP_REGTOT, LASER_NUMBER_CHAN_2);
		g_TempCurrentRealValue.TempCtrCurrent_Chn_1 = HAL_AD7689SpiReadTempOrTempCtrCurReal(ADC7689_LASER_TEMPCTR_CHAN_1, AD7689_LASER_TEMPCTRCUR_REGTOT, LASER_NUMBER_CHAN_1);
    g_TempCurrentRealValue.TempCtrCurrent_Chn_2 = HAL_AD7689SpiReadTempOrTempCtrCurReal(ADC7689_LASER_TEMPCTR_CHAN_2, AD7689_LASER_TEMPCTRCUR_REGTOT, LASER_NUMBER_CHAN_2);
		
		seedTemp = g_TempCurrentRealValue.Temperature_Chn_1;
		seedTempCur = g_TempCurrentRealValue.TempCtrCurrent_Chn_1;
		taTemp = g_TempCurrentRealValue.Temperature_Chn_2;
		taTempCur = g_TempCurrentRealValue.TempCtrCurrent_Chn_2;

    // 激光器种子电流读取 2ms
    g_TempCurrentRealValue.Current_Chn_1 = HAL_ADC1119I2cReadCurrentReal(LASER_NUMBER_CHAN_1, SAMPCUR_TYPE_WORK_CURRENT);
		seedCur = g_TempCurrentRealValue.Current_Chn_1;
	
		seedVoltage = HAL_ADC1119I2cReadCurrentReal(LASER_NUMBER_CHAN_1,SAMPCUR_TYPE_WORK_VOLTAGE);
	
		g_TempCurrentRealValue.Current_Chn_2 = HAL_ADC1119I2cReadCurrentReal(LASER_NUMBER_CHAN_2, SAMPCUR_TYPE_WORK_CURRENT);
		taCur = g_TempCurrentRealValue.Current_Chn_2;
		
		taVoltage = HAL_ADC1119I2cReadCurrentReal(LASER_NUMBER_CHAN_2,SAMPCUR_TYPE_WORK_VOLTAGE);
#if MODEL_CHOICE == MODEL_LASER_TA
    // 激光器TA - PD电流读取 4ms???
	//PD电流读取改为AD7689
		g_TempCurrentRealValue.Current_PD = HAL_AD7689SpiReadTempOrTempCtrCurReal(ADC7689_LASER_PDPOWER_CHAN_2,AD7689_LASER_PDPOWER_REGTOT,LASER_NUMBER_CHAN_2);
	
    //g_TempCurrentRealValue.Current_PD = HAL_ADC1119I2cReadCurrentReal(LASER_NUMBER_CHAN_2, SAMPCUR_TYPE_PD_CURRENT) + LASER_PD_CURRENT_ADD;
		pdCur = g_TempCurrentRealValue.Current_PD;
		//taVoltage = hal_ADS1119I2cCurrentRegtomA(taVoltage,LASER_NUMBER_CHAN_2,SAMPCUR_TYPE_WORK_CURRENT);
#elif MODEL_CHOICE == MODEL_LASER_DFB

#endif
	
	if(storeFlag)
	{
		seedCurrent[seedCurIndex++] = seedCur;
		taCurrent[taCurIndex++] = taCur;
		pdCurrent[pdCurIndex++] = pdCur;
	}
	
}

static void UartRcvDeal()
{
    // fix byme 如果MyQueue的count为0代表此时没有数据
    // 防止丢包 但是解决不了 粘包和错包的情况 后续需要改进
    if (!isQueueEmpty(&g_MyQueue))
    {
        struct TLVPacket MyQueue_packet;

        memset(&MyQueue_packet, 0, sizeof(struct TLVPacket));

        // 拷贝cmd length value
        dequeue(&g_MyQueue, &MyQueue_packet);

        ModuleDivide(&MyQueue_packet);
    }
}

static void DriverProtectDeal()
{
    /*
    电流源和温控芯片保护逻辑
	1、不管是电流源保护还是温度保护，都要先把电流降为0然后再关闭电流源和温控芯片
    2、电流异常/温度异常只要有一个异常就要关闭电流源和温控芯片，两个绑定在一起
    3、电流源关闭条件：
        a、电流大于设定值（硬件电路设置250mA就会保护（DBR），DFB为142，但是硬件电路没有设置，因此软件要进行判断）
        b、OVP（硬件电路触发）
        c、OCP（硬件电路触发）
    4、温控芯片关闭条件
        a、温度超出阈值范围（10 - 40），修改为 给定值超过阈值上下限的 5% 也就是 8 - 42 峰值 且连续采集N个数之后的平均值仍然超出峰值即认为需要温度保护
        b、OT/UT只是一个指示不代表异常
    */
#if MODEL_CHOICE == MODEL_LASER_TA

    if ((hal_LaserReadValueNormal(JUDGE_LASER_LIMIT_TYPE_TEMP, g_TempCurrentRealValue.Temperature_Chn_1, LASER_NUMBER_CHAN_1)) == 0 ||
        (hal_LaserReadValueNormal(JUDGE_LASER_LIMIT_TYPE_CURRENT_SEED, g_TempCurrentRealValue.Current_Chn_1, LASER_NUMBER_CHAN_1)) == 0)
    {
				protec_chn1 = 1;
        HAL_TempDrivePinDisEnable(LASER_NUMBER_CHAN_1);
        HAL_CurrentDrivePinDisEnable(LASER_NUMBER_CHAN_1);
        pritect_cnt[LASER_NUMBER_CHAN_1 - 1]++;
        if (pritect_cnt[LASER_NUMBER_CHAN_1 - 1] % LASER_PROTECT_LOG_TIMER == 1)
        {
            SLOG_I("laser num:%d TC error, close TC driver, temp: %.4f, current: %.4f\t\r\n", LASER_NUMBER_CHAN_1, 
            g_TempCurrentRealValue.Temperature_Chn_1, g_TempCurrentRealValue.Current_Chn_1);
        }
    }

    if ((hal_LaserReadValueNormal(JUDGE_LASER_LIMIT_TYPE_TEMP, g_TempCurrentRealValue.Temperature_Chn_2, LASER_NUMBER_CHAN_2) == 0) ||
        (hal_LaserReadValueNormal(JUDGE_LASER_LIMIT_TYPE_CURRENT_TA, g_TempCurrentRealValue.Current_Chn_2, LASER_NUMBER_CHAN_2) == 0) ||
        (hal_LaserReadValueNormal(JUDGE_LASER_LIMIT_TYPE_PD, g_TempCurrentRealValue.Current_PD, LASER_NUMBER_CHAN_2) == 0))
    {
				protec_chn2 = 1;
        TA_CHANNEL_LD_ON_PIN_STATE = GPIO_PIN_RESET;
        HAL_TempDrivePinDisEnable(LASER_NUMBER_CHAN_2);
        HAL_CurrentDrivePinDisEnable(LASER_NUMBER_CHAN_2);
        pritect_cnt[LASER_NUMBER_CHAN_2 - 1]++;
        if (pritect_cnt[LASER_NUMBER_CHAN_2 - 1] % LASER_PROTECT_LOG_TIMER == 1)
        {
            SLOG_I("laser num:%d TC error, close TC driver, temp: %.4f, current: %.4f, pd: %.4f \t\r\n", LASER_NUMBER_CHAN_2, 
            g_TempCurrentRealValue.Temperature_Chn_2, g_TempCurrentRealValue.Current_Chn_2, g_TempCurrentRealValue.Current_PD);
        }
    }

#elif MODEL_CHOICE == MODEL_LASER_DFB

    if ((hal_LaserReadValueNormal(JUDGE_LASER_LIMIT_TYPE_TEMP, g_TempCurrentRealValue.Temperature_Chn_1, LASER_NUMBER_CHAN_1) == 0) ||
        (hal_LaserReadValueNormal(JUDGE_LASER_LIMIT_TYPE_CURRENT_SEED, g_TempCurrentRealValue.Current_Chn_1, LASER_NUMBER_CHAN_1) == 0))
    {
        HAL_TempDrivePinDisEnable(LASER_NUMBER_CHAN_1);
        HAL_CurrentDrivePinDisEnable(LASER_NUMBER_CHAN_1);
        pritect_cnt[LASER_NUMBER_CHAN_1 - 1]++;
        if (pritect_cnt[LASER_NUMBER_CHAN_1 - 1] % LASER_PROTECT_LOG_TIMER == 1)
        {
            SLOG_I("laser num:%d TC error, close TC driver, temp: %.4f, current: %.4f\t\r\n", LASER_NUMBER_CHAN_1,
            g_TempCurrentRealValue.Temperature_Chn_1, g_TempCurrentRealValue.Current_Chn_1);        
        }
    }

    if ((hal_LaserReadValueNormal(JUDGE_LASER_LIMIT_TYPE_TEMP, g_TempCurrentRealValue.Temperature_Chn_2, LASER_NUMBER_CHAN_2) == 0) ||
        (hal_LaserReadValueNormal(JUDGE_LASER_LIMIT_TYPE_CURRENT_SEED, g_TempCurrentRealValue.Current_Chn_2, LASER_NUMBER_CHAN_2) == 0))
    {
        HAL_TempDrivePinDisEnable(LASER_NUMBER_CHAN_2);
        HAL_CurrentDrivePinDisEnable(LASER_NUMBER_CHAN_2);
        pritect_cnt[LASER_NUMBER_CHAN_2 - 1]++;
        if (pritect_cnt[LASER_NUMBER_CHAN_2 - 1] % LASER_PROTECT_LOG_TIMER == 1)
        {
            SLOG_I("laser num:%d TC error, close TC driver, temp: %.4f, current: %.4f \t\r\n", LASER_NUMBER_CHAN_2,
            g_TempCurrentRealValue.Temperature_Chn_2, g_TempCurrentRealValue.Current_Chn_2);        
        }
    }
#endif
}